package de.fuberlin.inf.alp3.ue02;

public class Theatre implements Reservable {
    boolean[][] hall;

    public Theatre() {
        this(5, 8);
    }
    public Theatre(int rows, int seats) {
        if ((rows > 26) || 1 > rows || 1 > seats)
            throw new RuntimeException("26 rows supported");
        this.hall = new boolean[rows][seats];
    }
    @Override
    public boolean cancel(char row, int seatFrom, int seatTo) {
        return setTo(row, seatFrom, seatTo, false);
    }
    private boolean setTo(char row, int seatFrom, int seatTo, boolean b) {
        if (('a' <= row) && ('z' >= row))
            row -= 32;
        if (!validParams(row, seatFrom, seatTo))
            return false;
        boolean contrary = true;
        for (int i = (seatFrom - 1); i <= (seatTo - 1); i++)
            if (hall[(row - 65)][i] == b) {
                contrary = false;
                break;
            }
        if (contrary) {
            for (int i = (seatFrom - 1); i <= (seatTo - 1); i++)
                hall[(row - 65)][i] = b;
            return true;
        } else
            return false;
    }
    @Override
    public char getMaxRow() {
        return ((char) (hall.length + 96));
    }
    @Override
    public int getMaxSeat() {
        return hall[0].length;
    }
    @Override
    public boolean reserve(char row, int seatFrom, int seatTo) {
        return setTo(row, seatFrom, seatTo, true);
    }
    private boolean validParams(char row, int seatFrom, int seatTo) {
        if ((65 > row) || (getMaxRow() < row))
            return false;
        if (1 > seatFrom || getMaxSeat() < seatTo || seatFrom > seatTo)
            return false;
        return true;
    }
    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("   ");
        for (int i = 0; i < this.hall[0].length;)
            sb.append(" " + ++i);
        for (int i = 0; i < this.hall.length; i++) {
            sb.append("\n " + ((char) (65+i)) + "  ");
            for (int j = 0; j < this.hall[i].length; j++)
                sb.append(((hall[i][j]) ? "X" : "-")+((j > 8) ? "  " : " "));
        }
        return sb.toString();
    }
}